import { useContext } from "react";
import { NavigationContext, LocationContext } from "./context";
/*
  const navigate = useNavigate()
  navigate('/home')
  
  返回值是一个函数，调用函数完成路由跳转
*/
export const useNavigate = () => {
  const { navigator } = useContext(NavigationContext);

  return (to) => {
    // 跳转路由
    // history.push() / history.replace()
    navigator.push(to);
  };
};

export const useLocation = () => {
  const { location } = useContext(LocationContext);
  return location;
};

export const useRoutes = (routes) => {
  /*
    1. 
      [
        路由组件1，
        路由组件2，
        路由组件3，
        ...
      ]
      问题：会渲染所有路由组件
      解决：只渲染当前路由路径对应的路由组件

    2. 
  */
  const location = useLocation();

  return routes.map((route) => {
    if (location.pathname !== route.path) return null;
    // 说明当前路由路径和route.path相等，返回渲染路由组件
    return <div key={route.path}>{route.element}</div>;
  });
};
